package titt.server.os;

import java.util.UUID;

import titt.head.HTTPHead;
import titt.head.HeadFactory;
import titt.head.Header;
import titt.io.IOFactory;
import titt.io.encoding.EncodingFacade;
import titt.server.internal.ServerInternal;
import titt.server.service.db.ServerDatabase;
import titt.util.io.pipe.StreamPiper;

public class ObjectServer {

	private StreamPiper piper = IOFactory.createStreamPiper();
	private EncodingFacade ef = IOFactory.createEncodingFacade();
	private ServerDatabase db;
	private ServerInternal internal = new ServerInternal(this);
	private String type;
	
	private final Header 	SERVER = new Header("Server", "TITT"),
							PRAGMA = new Header("Pragma", "no-cache"),
							CACHE = new Header("Cache-Control", "no-cache"),
							EXPIRATION = new Header("Expires", "-1");
	
	private long inc = 0;
		
	public ObjectServer(String type) {
		this.type = type;
	}

	public void setServerDatabase(ServerDatabase db) {
		this.db = db;		
	}
	
	public EncodingFacade getEncodingFacade() {
		return ef;
	}
	
	public StreamPiper getStreamPiper() {
		return piper;
	}
	
	public ServerDatabase getServerDatabase() {
		return db;
	}
	
	public ServerInternal getServerInternal() {
		return internal;
	}
	
	public String getType() {
		return type;
	}
	
	public HTTPHead addResponseHeaders(HTTPHead h) {
		if(h.getHeader("Content-Disposition") != null) //quick patch for IE7 to allow opening of files
			return HeadFactory.createHead(h, SERVER, EXPIRATION);
		
		//no cache for standard calls - TODO: Maybe move cache behaviour to TITT or check for other cache set to override it
		return HeadFactory.createHead(h, SERVER, PRAGMA, CACHE, EXPIRATION);
	}
	
	public synchronized String generateID(boolean strong) {
		return strong? UUID.randomUUID().toString() : "" + Math.abs(inc++);
	}
}
